<template>
  <div class="video">
    <div class="videoMain">
      <div class="goBack" @click="setVideo(false)">
        <img src="../../../assets/images/goBack.png" alt="" />返回
      </div>
      <div class="videoTiele">{{ currentObj.title }}</div>
      <div class="videoCnt">
        <div class="player">
          <video-player
            v-if="currentObj.type === '视频'"
            ref="videoPlayer"
            class="video-player vjs-custom-skin"
            :playsinline="true"
            :options="playOptions"
            @play="onPlayerPlay($event)"
            @pause="onPlayerPause($event)"
            @timeupdate="onPlayerTimeupdate($event)"
          />
          <div class="pdf-scale-box" v-if="currentObj.type === 'PDF' && pdfUrl">
            <pdf :src="pdfUrl" :page="currentPage" @num-pages="getTotalPage">
            </pdf>
          </div>
          <div v-if="currentObj.type === 'PDF' && pdfUrl" class="fixedBtn">
            <div class="total">共 {{ pageTotal }} 页</div>
            <div class="total">第 {{ currentPage }} 页</div>
            <el-button-group>
              <el-button
                type="primary"
                icon="el-icon-arrow-left"
                size="mini"
                :disabled="currentPage === 1"
                @click="chengPage"
                >上一页</el-button
              >
              <el-button
                type="primary"
                size="mini"
                :disabled="currentPage === pageTotal"
                @click="chengPage('+')"
                >下一页<i class="el-icon-arrow-right el-icon--right"></i
              ></el-button>
            </el-button-group>
          </div>
        </div>
        <div class="videoList">
          <div class="title">课件列表：</div>
          <div class="videoListMain">
            <div
              :class="[
                'videoItem',
                item.id === currentObj.id ? 'isActive' : null,
              ]"
              v-for="item in list"
              :key="item.id"
              @click="setData(item, true)"
            >
              <img
                src="../../../assets/images/video.png"
                alt=""
                v-if="item.type === '视频'"
              />
              <span class="imgPdf" v-else>PDF</span>
              <div>
                <div>{{item.title}}</div>
                <div>
                  <span v-if="item.type === '视频'">时长：{{ convertSecondsToHMS(item.length) }}</span>
                  <span v-else>页数：{{ item.length }}页</span>
                  <span>{{
                    item.status === "0"
                      ? "未开始"
                      : item.status === "1"
                      ? "学习中"
                      : "已完成"
                  }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { endStudy } from "@/api/trainingCenter";
import pdf from "vue-pdf";
export default {
  components: {
    pdf,
  },
  props: {
    currentData: {
      type: Object,
      default: () => {},
    },
    path: {
      // 传入的地址
      type: String,
      default: "",
    },
    getList: {
      type: Function,
      default: () => {},
    },
  },
  inject: ["setVideo"],
  data() {
    return {
      pdfUrl: "",
      pageTotal: 0,
      currentPage: 1,
      pageChangeTimer: null,
      list: [],
      currentObj: {},
      playedTime: 0,
      currentTime: 0,
      maxTime: 0,
      playOptions: {
        width: "100%",
        playbackRates: [1.0, 1.5, 2.0, 3.0], // 可选的播放速度
        autoplay: false, // 如果为true,浏览器准备好时开始回放
        muted: false, // 默认情况下静音播放
        loop: false, // 是否视频一结束就重新开始
        preload: "auto", // 建议浏览器在<video>加载元素后是否应该开始下载视频数据，auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
        language: "zh-CN",

        aspectRatio: "16:9", // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值，值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
        fluid: true, // 当true时，Video.js player将拥有流体大小，换句话说，它将按比例缩放以适应其容器
        flash: { hls: { withCreadentials: false } }, //可以播放rtmp视频
        html5: { hls: { withCreadentials: false } }, //可以播放m3u8视频
        sources: [
          {
            // withCredentials: true,
            // type: "application/x-mpegURL",
            // src: "/dev-api/profile/2024/09/29/911Mothers_2010W-light_20240929165831A001.mp4",
          },
        ],
        hls: {
          withCredentials: true,
        },
        poster: "../../../assets/images/banner1.png", // 设置封面地址
        notSupportedMessage: "此视频暂无法播放，请稍后再试", // 允许覆盖Video.js无法播放媒体源时显示的默认信息
        controlBar: {
          currentTimeDisplay: true,
          progressControl: true, // 是否显示进度条
          playbackRateMenuButton: true, // 是否显示调整播放倍速按钮
          timeDivider: true, // 当前时间和持续时间的分隔符
          durationDisplay: true, // 显示持续时间
          remainingTimeDisplay: true, // 是否显示剩余时间功能
          fullscreenToggle: true, // 是否显示全屏按钮
        },
      },
    };
  },
  computed: {},
  async mounted() {
    this.list = await this.getList();
    this.setData(this.currentData);
  },
  methods: {
    chengPage(type) {
      if (this.pageChangeTimer) {
        clearTimeout(this.pageChangeTimer);
      }
      this.pageChangeTimer = setTimeout(() => {
        if (type === "+") {
          this.currentPage += 1;
        } else {
          this.currentPage -= 1;
        }
        this.scrollbarReset();
        this.pageChangeTimer = null;
      }, 500);
    },

    scrollbarReset() {
      let boxDom = document.querySelector(".pdf-scale-box");
      boxDom.scrollTop = 0;
    },
    getTotalPage(page) {
      this.pageTotal = page;
    },
    async endStudyFun() {
      await endStudy(this.currentObj.trainPlanCoursewareDetailId, {
        studyTime: this.currentTime,
      });
      this.list = await this.getList();
    },
    async setData(data, isApi) {
      if (this.currentObj.id === data.id) return;
      if (data.type === "PDF") {
        this.currentObj = data;
        this.currentPage = 1;
        const url = JSON.parse(this.currentObj.object)[0].url;
        this.pdfUrl = url;
      } else {
        if (isApi) {
          await this.endStudyFun();
        }
        this.currentObj = data;
        if (this.currentObj.object) {
          const url = JSON.parse(this.currentObj.object)[0].url;
          this.playedTime = this.currentObj.studyTime;
          this.currentTime = 0;

          this.playOptions.sources = [{ src: url }];
          this.$refs.videoPlayer?.player?.reset();
        }
      }
    },
    // 视频播放
    async onPlayerPlay(player) {
      player.currentTime(this.playedTime);
    },
    // 视频暂停的
    onPlayerPause(player) {
      this.playedTime = player.currentTime();
    },
    // 当前播放位置发生变化时触发
    onPlayerTimeupdate(player) {
      this.currentTime = player.currentTime();
    },
    // 手动暂停视频的播放
    pause() {
      this.$refs.videoPlayer.player.pause();
    },
    getImg(data) {
      let img = undefined;
      if (!!data) {
        img = JSON.parse(data);
      }
      if (img?.length) {
        return img[0].url;
      }
      return require("../../../assets/images/banner1.png");
    },
    convertSecondsToHMS(seconds) {
      if (!isNaN(Number(seconds))) {
        var hours = String(Math.floor(Number(seconds) / 3600));
        var minutes = String(Math.floor((Number(seconds) % 3600) / 60));
        var remainingSeconds = String(Number(seconds) % 60);
        hours = hours.length === 1 ? `0${hours}` : hours;
        minutes = minutes.length === 1 ? `0${minutes}` : minutes;
        remainingSeconds =
          remainingSeconds.length === 1
            ? `0${remainingSeconds}`
            : remainingSeconds;
        return hours + ": " + minutes + ": " + remainingSeconds;
      }
      return "00" + ": " + "00" + ": " + "00";
    },
  },
  async beforeDestroy() {
    await this.endStudyFun();
  },
};
</script>

<style lang="scss" scoped>
.video {
  background: #f4f4f4;
  display: flex;
  justify-content: center;
  font-family: Microsoft YaHei;
  font-weight: 400;
  min-height: calc(100vh - 90px);
  ::v-deep .vjs-progress-control {
    pointer-events: none !important;
  }
  .imgPdf {
    display: inline-block;
    width: 24px;
    height: 24px;
    background: #ff4d4f;
    text-align: center;
    line-height: 24px;
    color: #fff;
    font-size: 10px;
    border-radius: 10px;
    margin-right: 13px;
  }
  .videoMain {
    padding-top: 20px;
    width: calc(100% - 290px);
    .videoCnt {
      display: flex;
      .player {
        width: 80%;
        margin-right: 14px;
        position: relative;
        .fixedBtn {
          display: flex;
          justify-content: space-between;
          padding: 5px 20px;
          // background: #c0d8f4;
          align-items: center;
          border-radius: 0 0 8px 8px;
          .total {
            font-size: 14px;
            color: #666;
          }
        }
      }
      .videoList {
        width: 400px;
        height: 73vh;
        overflow-y: auto;
        background: #fff;
        .title {
          padding: 20px 18px;
          border-bottom: 1px solid #c6c6c6;
        }
        .videoListMain {
          padding: 18px;

          .videoItem {
            margin-top: 10px;
            display: flex;
            align-items: start;
            background: #f8f8f8;
            border-radius: 6px;
            padding: 18px;
            cursor: pointer;
            &:hover {
              background: #f5f8fe;
            }
            img {
              width: 24px;
              height: 24px;
              margin-right: 13px;
            }
            & > div {
              & > div:nth-of-type(1) {
                font-size: 16px;
                color: #333333;
                margin-bottom: 18px;
              }
              & > div:nth-of-type(2) {
                display: flex;
                justify-content: space-between;
                align-items: center;
                & > span {
                  font-size: 14px;
                  color: #999999;
                }
              }
            }
          }
          .isActive {
            background: #dfe5f7;
            &:hover {
              background: #dfe5f7;
            }
          }
        }
        .isactive {
          & > div {
            & > div:nth-of-type(1) {
              color: #2f54eb !important;
            }
            & > div:nth-of-type(2) {
              & > span {
                color: #2f54eb !important;
              }
            }
          }
        }
      }
    }
  }
  .goBack {
    font-size: 14px;
    color: #8b8b8b;
    margin: 0 0 30px 0;
    cursor: pointer;
    img {
      width: 17px;
      height: 15px;
      margin-right: 6px;
    }
  }
  .videoTiele {
    font-size: 22px;
    color: #000000;
    margin-bottom: 30px;
  }
  .pdf-scale-box {
    height: 700px;
    overflow: auto;
  }
}
</style>